package com.bnlr.lrparking.appui.message;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.adapter.HeaderAndFooterRecyclerViewAdapter;
import com.bnlr.lrparking.appui.web.WebActivity;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.model.BaseArrayBean;
import com.bnlr.lrparking.model.MessageM;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.lrparking.util.CommonUtil;
import com.bnlr.lrparking.widget.refresh.RefreshHolderUtil;
import com.bnlr.lrparking.widget.refresh.XRefreshLayout;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.yolanda.nohttp.NoHttp;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 消息中心
 *
 * @author  Administrator
 * @date  2017/5/4
 */

public class MyMessageActivity extends BaseActivity {


    @BindView(R.id.message_line)
    View messageLine;
    @BindView(R.id.lv_message_list)
    RecyclerView lvMessageList;
    @BindView(R.id.rl_message_refresh)
    XRefreshLayout rlMessageRefresh;
    @BindView(R.id.iv_hint)
    ImageView ivHint;
    @BindView(R.id.tv_hint_tips)
    TextView tvHintTips;
    @BindView(R.id.ll_hint)
    LinearLayout llHint;
    @BindView(R.id.tv_nav_title)
    TextView tvNavTitle;

    private View footView;
    private TextView tv_foot;
    MessageAdapter adapter;
    List<MessageM.DataBean> messageList = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_message);
        ButterKnife.bind(this);
        initView();
        tvNavTitle.setText("消息中心");
    }

    /**
     * 初始化页面
     */
    public void initView() {
        footView = View.inflate(baseContext, R.layout.layout_footview, null);
        tv_foot = (TextView) footView.findViewById(R.id.tv_foot);
        footView.setVisibility(View.GONE);
        linearLayoutManager = new LinearLayoutManager(baseContext);
        lvMessageList.setLayoutManager(linearLayoutManager);
        lvMessageList.setItemAnimator(new DefaultItemAnimator());
        adapter = new MessageAdapter(baseContext, R.layout.item_message, messageList);
        headerAndFooterAdapter = new HeaderAndFooterRecyclerViewAdapter(adapter);
        headerAndFooterAdapter.addFooterView(footView);
        lvMessageList.setAdapter(headerAndFooterAdapter);
        rlMessageRefresh.setRefreshViewHolder(RefreshHolderUtil.getRefreshHolder(this));
        rlMessageRefresh.setDelegate(new XRefreshLayout.BGARefreshLayoutDelegate() {
            @Override
            public void onBGARefreshLayoutBeginRefreshing(XRefreshLayout refreshLayout) {
                footView.setVisibility(View.GONE);
                if (messageList.size() > 0) {
                    messageList.clear();
                    adapter.notifyDataSetChanged();
                }
                pageNum = 1;
                getData();
            }

            @Override
            public boolean onBGARefreshLayoutBeginLoadingMore(XRefreshLayout refreshLayout) {
                return false;
            }

        });
        rlMessageRefresh.beginRefreshing();

        lvMessageList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int total = linearLayoutManager.getItemCount();
                int lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
                //lastVisibleItem >= totalItemCount - 4 表示剩下4个item自动加载，各位自由选择
                // dy > 0 表示向下滑动
                if (lastVisibleItem >= total - 4 && dy > 0) {
                    if (!isLoadingMore) {
                        isLoadingMore = true;

                        getData();
                    }
                }
            }
        });

        lvMessageList.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return rlMessageRefresh.isRefreshing();
            }
        });
    }

    @Override
    public void getData() {
        super.getData();

        try {
            if (CommonUtil.isNetworkAvailable(baseContext) == 0) {
                CommonUtil.showToask(baseContext, "当前无网络连接，请检查网络设置");
                return;
            }

            mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
            mRequest.add("action", "GetMessage");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("uid", AppConfig.getInstance().getString("uid",""));
            mRequest.add("index", pageNum);
            CallServer.getRequestInstance().add(this, mRequest,
                    new CustomHttpListener<MessageM>(this, true, MessageM.class) {

                        @Override
                        public void doWork(MessageM data, String code) {
                            if ("1".equals(code)) {
                                if (data.getData().size() < 10) {
                                    footView.setVisibility(View.VISIBLE);
                                    tv_foot.setText("没有更多消息了");
                                } else {
                                    footView.setVisibility(View.VISIBLE);
                                    tv_foot.setText(R.string.foot_more);
                                }
                                pageNum++;
                                messageList.addAll(data.getData());
                                adapter.notifyDataSetChanged();
                            }
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            rlMessageRefresh.endRefreshing();
                            isLoadingMore = false;
                            if (messageList.size() == 0) {
                                llHint.setVisibility(View.VISIBLE);
                                ivHint.setBackgroundResource(R.mipmap.icon_empt);
                                tvHintTips.setText("暂无消息哦~");
                            } else {
                                llHint.setVisibility(View.GONE);
                                if (!TextUtils.equals("1", code) && pageNum != 1) {
                                    footView.setVisibility(View.VISIBLE);
                                    tv_foot.setText("没有更多消息了");
                                }
                            }
                        }
                    }, false);
        } catch (Exception e) {
        }


    }

    public class MessageAdapter extends CommonAdapter<MessageM.DataBean> {

        public MessageAdapter(Context context, int layoutId, List<MessageM.DataBean> datas) {
            super(context, layoutId, datas);
        }

        @Override
        protected void convert(final ViewHolder holder, final MessageM.DataBean s, final int position) {

            holder.setText(R.id.message_title, s.getTitle());
            holder.setText(R.id.message_centent, s.getContent());
            String[] date = s.getSendTime().split(" ");
            if (date.length > 0) {
                holder.setText(R.id.message_time,date[0]);
            } else {
                holder.setText(R.id.message_time,s.getSendTime());
            }

            //未读
            if ("0".equals(s.getIsRead())) {
                holder.setVisible(R.id.tv_message_dian, true);
                holder.setTextColorRes(R.id.message_title,R.color.text_color);
                holder.setTextColorRes(R.id.message_centent,R.color.text_color);
                holder.setTextColorRes(R.id.message_time,R.color.gray03_color);
            }
            //已读
            else if ("1".equals(s.getIsRead())){
                holder.setVisible(R.id.tv_message_dian, false);
                holder.setTextColorRes(R.id.message_title,R.color.gray03_color);
                holder.setTextColorRes(R.id.message_centent,R.color.gray03_color);
                holder.setTextColorRes(R.id.message_time,R.color.gray03_color);
            }

            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if ("0".equals(messageList.get(position).getIsRead())) {
                        setReaded(position);
                    }
                    Intent intent = new Intent(baseContext, WebActivity.class);
                    intent.putExtra("tag", 5);
                    intent.putExtra("id", s.getId());
                    startActivity(intent);
                }
            });

        }
    }


    /**
     *
     *
     * @param position
     */
    private void setReaded(final int position) {
        try {
            mRequest = NoHttp.createStringRequest(Urls.MESSAGE, LrConstant.POST);
            mRequest.add("action", "SetMessageReaded");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("uid", AppConfig.getInstance().getString("uid",""));
            mRequest.add("id", messageList.get(position).getId());
            CallServer.getRequestInstance().add(this, mRequest,
                    new CustomHttpListener<BaseArrayBean>(this, true, BaseArrayBean.class) {

                        @Override
                        public void doWork(BaseArrayBean data, String code) {
                            if ("1".equals(code)) {
                                messageList.get(position).setIsRead("1");
                                adapter.notifyDataSetChanged();
                            }
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    }, false);
        } catch (Exception e) {
        }

    }
}
